package com.fengmang.myapplication;

import android.Manifest;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;


import androidx.core.app.ActivityCompat;

import com.smartapp.update.BatchUtils;
import com.smartapp.update.Utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.ZipInputStream;



/**
 * 自定义Application
 * 
 * @author wutao
 *
 */
public class BaseApplication
		extends Application
//		extends MultiDexApplication        //TODO
		{
	public static String mode = "";	//"t":改密钥密码模式 	"":正常模式

	public  static Context context;
	private static BaseApplication app;
	public static int width;
	public static int height;
	public static float density;
	public static Typeface font;


	public static int school_id;
	public static int school_id2;
	public static String school_name;
	public static String school_latitude = "";	//用户管辖城市纬度
	public static String school_longitude = "";	//用户管辖城市经度
	public static int[] school_carmodel_ids;

	static {
		System.loadLibrary("SmartAppUpdate");
	}


	// 合成成功
	private static final int SUCCESS = 1;
	// 合成的APK签名和已安装的签名不一致
	private static final int FAIL_SING = -1;
	// 合成失败
	private static final int FAIL_ERROR = -2;
	// 获取源文件失败
	private static final int FAIL_GET_SOURCE = -3;
	public static final String PATH = Environment.getExternalStorageDirectory() + File.separator;
	public static final String NEW_APK_PATH = PATH + "myhotfix.apk";
	//	public static final String NEW_APK_PATH = PATH + "bsdiff_old.apk";
	public static final String PATCH_PATH = PATH + "myhotfix.patch";

	private PackageInfo packageInfo;

	public BaseApplication() {
		app = this;
	}

	public static synchronized BaseApplication getInstance() {
		if (app == null) {
			app = new BaseApplication();
		}
		return app;
	}

	@Override
	protected void attachBaseContext(Context base) {
		super.attachBaseContext(base);
//		MultiDex.install(this);
	}

	@Override
	public void onCreate() {
		super.onCreate();
		context = this;

//		File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "app-debug.apk");
//		File file = new File("/data/data/com.fengmang.myapplication/app-debug.apk");
//
//		if(file.exists()){
//			Amigo.workLater(this, file);
////                if(it){
////                    toast("更新成功！")
////
////                    Intent intent = packageManager.getLaunchIntentForPackage(packageName)
////
////                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
////
////                    startActivity(intent)
////
////                    android.os.Process.killProcess(android.os.Process.myPid())
////
////                }
//		}

		DisplayMetrics metrics = new DisplayMetrics();
		WindowManager wm = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
		wm.getDefaultDisplay().getMetrics(metrics);
		density = metrics.density;
		width = metrics.widthPixels;
		height = metrics.heightPixels;

//		font = Typeface.createFromAsset(getAssets(),"simkai.ttf");

		Log.e("ba===",width + "===" + density);

//		SharedPreferencesUrls.getInstance().putString("access_token", "");
//		ToastUtils.init(this);
//		initImageLoader(getApplicationContext());

		Log.e("ba===1", "==="+PluginManager.getInstance().getResources());



		Log.e("ba===2", "==="+PluginManager.getInstance().getResources());

//		File dexPath = new File(getDir("dex", Context.MODE_PRIVATE), "path_dex.jar");
//		Log.e("mainHHH","dexPath = " + dexPath.getAbsolutePath());
//		Utils.prepareDex(getApplicationContext(), dexPath, "path_dex.jar");
//		HotFix.patch(getApplicationContext(), dexPath.getAbsolutePath(), "");

		//先修复bug
//		HotFix.patch(getApplicationContext());
//		PluginManager.getInstance().loadPath(this);

//		ToastUtil.showMessageApp(this, "xxx3");


		//再异步下载apk，为插件化activity修复做准备
		new Thread(new Runnable() {
			@Override
			public void run() {


//				download();

			}
		}).start();


//		new UpdateApkTask().execute();
//		PluginManager.getInstance().loadPath2(this);
	}




	private class UpdateApkTask extends AsyncTask<String, Void, Integer> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
//			progressDialog.show();
		}

		@Override
		protected Integer doInBackground(String... params) {
			String oldApkSource = Utils.getSourceApkPath(context, getPackageName());

			Log.e("doInBackground===", "==="+oldApkSource);

			File file = new File(PATH,"SmartAppUpdate.patch");
			File newFile = new File(PATH,"SmartAppUpdate.apk");

			Log.e("doInBackground===1", file+"==="+file.exists()+"==="+newFile.exists());

//			return SUCCESS;
//			Utils.installApk(MainActivity.this, NEW_APK_PATH);

			if (!TextUtils.isEmpty(oldApkSource)) {
				int patchResult = -1;
				try {
					patchResult = BatchUtils.applyPatchToOwn(context, NEW_APK_PATH, PATCH_PATH);

					Log.e("doInBackground===2", file+"==="+file.exists()+"==="+newFile.exists());
				} catch (IOException e) {

					e.printStackTrace();
				}
				if (patchResult == 0) {
//					String signatureNew = Utils.getUnInstalledApkSignature(NEW_APK_PATH);
//					String signatureSource = Utils.getInstalledApkSignature(MainActivity.this, getPackageName());
//					if (!TextUtils.isEmpty(signatureNew) && !TextUtils.isEmpty(signatureSource) && signatureNew.equals(signatureSource)) {
//						return SUCCESS;
//					} else {
//						return FAIL_SING;
//					}

					return SUCCESS;
				} else {
					return FAIL_ERROR;
				}
			} else {
				return FAIL_GET_SOURCE;
			}
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
//			if (progressDialog.isShowing()) {
//				progressDialog.dismiss();
//			}
			switch (result) {
				case SUCCESS:
					showShortToast("新apk已合成成功：" + NEW_APK_PATH);
//					Utils.installApk(MainActivity.this, PATH + "SmartAppUpdate.apk");
//					Utils.installApk(context, NEW_APK_PATH);

//					RxAppTool.installApp(MainActivity.this, PATH + "SmartAppUpdate.apk");
//					RxAppTool.installApp(MainActivity.this, NEW_APK_PATH);

					break;
				case FAIL_SING:
					showShortToast("新apk已合成失败，签名不一致");
					break;
				case FAIL_ERROR:
					showShortToast("新apk已合成失败");
					break;
				case FAIL_GET_SOURCE:
					showShortToast("无法获取packageName为" + getPackageName()
							+ "的源apk文件，只能整包更新了！");
					break;
			}
		}
	}

	private void showShortToast(final String text) {
		Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
	}

//	HttpURLConnection connection;
//	ZipInputStream zipIn;
//	void download() {
//		try {
//
//			//在sd卡建存放ui包解压后文件的文件夹
////            File folderRoot = new File(folderPath);
////            folderRoot.mkdirs();
//
////            delFile(folderRoot);
//
//			Log.e("ma===download", "===");
//
////            URL mUrl = new URL("http://192.168.0.104:8080/web2/images/bug.class");
////			URL mUrl = new URL("http://192.168.0.104:8080/web2/images/path_dex.jar");
//			URL mUrl = new URL(Urls.host+"/web2/images/app-debug.apk");
//
//			connection = (HttpURLConnection) mUrl.openConnection();
//			Log.e("ma===download2", "===");
//
////            connection.setRequestProperty("Content-Length", "" + connection.getContentLength());
//			connection.setRequestMethod("GET");
//			//不使用缓存
//			connection.setUseCaches(false);
//			//设置超时时间
//			connection.setConnectTimeout(10000);
//			//设置读取超时时间
//			connection.setReadTimeout(10000);
//			//设置是否从httpUrlConnection读入，默认情况下是true;
//			connection.setDoInput(true);
//
//			Log.e("download===1", "==="+connection.getInputStream());
//
//
//
//			int readedBytes = 0;
//			byte[] downLoadBuffer = new byte[1024];
//
////            InputStream is = connection.getInputStream();
////            BufferedInputStream bis = new BufferedInputStream(is);
////            FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory()+ File.separator+"bug.class");
////            BufferedOutputStream bos= new BufferedOutputStream(fos);
////
////            while ((readedBytes = bis.read(downLoadBuffer)) > 0) {
////                bos.write(downLoadBuffer, 0, readedBytes);
////            }
//
//			InputStream is = connection.getInputStream();
////			FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory()+ File.separator+"app-debug.apk");
//			FileOutputStream fos = new FileOutputStream(getDir("dex", Context.MODE_PRIVATE).getAbsolutePath() + File.separator + "app-debug.apk");
//
//			while ((readedBytes = is.read(downLoadBuffer)) > 0) {
//				fos.write(downLoadBuffer, 0, readedBytes);
//			}
//
//			fos.close();
//			is.close();
//
//
//
//			mUrl = new URL(Urls.host+"/web2/images/app-debug2.apk");
//
//			connection = (HttpURLConnection) mUrl.openConnection();
//			Log.e("ma===download2", "===");
//
////            connection.setRequestProperty("Content-Length", "" + connection.getContentLength());
//			connection.setRequestMethod("GET");
//			//不使用缓存
//			connection.setUseCaches(false);
//			//设置超时时间
//			connection.setConnectTimeout(10000);
//			//设置读取超时时间
//			connection.setReadTimeout(10000);
//			//设置是否从httpUrlConnection读入，默认情况下是true;
//			connection.setDoInput(true);
//
//			Log.e("download===1", "==="+connection.getInputStream());
//
//
//
//			readedBytes = 0;
//			downLoadBuffer = new byte[1024];
//
////            InputStream is = connection.getInputStream();
////            BufferedInputStream bis = new BufferedInputStream(is);
////            FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory()+ File.separator+"bug.class");
////            BufferedOutputStream bos= new BufferedOutputStream(fos);
////
////            while ((readedBytes = bis.read(downLoadBuffer)) > 0) {
////                bos.write(downLoadBuffer, 0, readedBytes);
////            }
//
//			is = connection.getInputStream();
////			fos = new FileOutputStream(Environment.getExternalStorageDirectory()+ File.separator+"app-debug2.apk");
//			fos = new FileOutputStream(getDir("apk", Context.MODE_PRIVATE).getAbsolutePath() + File.separator + "app-debug2.apk");
//
//			while ((readedBytes = is.read(downLoadBuffer)) > 0) {
//				fos.write(downLoadBuffer, 0, readedBytes);
//			}
//
//			fos.close();
//			is.close();
//
//
//
////			HotFix.patch(getApplicationContext());
//			PluginManager.getInstance().loadPath(this);
//
////			HotFix.patch(getApplicationContext());
//
//			Log.e("download===2", "===");
//
////            List<String> list = new ArrayList();
////            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
////                zipIn = new ZipInputStream(connection.getInputStream(), Charset.forName("GBK"));    //url输入流转为zip输入流
////            } else {
////                zipIn = new ZipInputStream(connection.getInputStream());
////            }
////
////            while ((zipEntry = zipIn.getNextEntry()) != null) {
////            }
//		}catch (Exception e){
//			Log.e("download===e", "==="+e);
//
//		}
//	}

//	private static void initImageLoader(Context context) {
//
//		File cacheDir = StorageUtils.getCacheDirectory(context);
//
//		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
//				.memoryCacheExtraOptions(480, 800) // maxwidth, max
//				// height，即保存的每个缓存文件的最大长宽
//				.threadPoolSize(3)// 线程池内加载的数量
//				.threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory()
//				.memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) // 你可以通过自己的内存缓存实现
//				.memoryCacheSize(2 * 1024 * 1024).diskCacheSize(50 * 1024 * 1024)
//				.diskCacheFileNameGenerator(new Md5FileNameGenerator())// 将保存的时候的URI名称用MD5加密
//				.tasksProcessingOrder(QueueProcessingType.LIFO).diskCacheFileCount(100) // 缓存的文件数量
//				.diskCache(new UnlimitedDiskCache(cacheDir))// 自定义缓存路径
//				.defaultDisplayImageOptions(DisplayImageOptions.createSimple())
//				.imageDownloader(new BaseImageDownloader(context, 5 * 1000, 30 * 1000)) // connectTimeout(5s),readTimeout(30s)超时时间
//				.writeDebugLogs() // Remove for releaseapp
//				.build();// 开始构建
//
//		ImageLoader.getInstance().init(config);
//	}

//	// 注册App异常崩溃处理器
//	private void registerUncaughtExceptionHandler() {
//		Thread.setDefaultUncaughtExceptionHandler(AppException.getAppExceptionHandler());
//	}

	@Override
	public void onLowMemory() {
		super.onLowMemory();
		System.gc();
	}

}
